package org.example.project_12.service.impl;

import org.example.project_12.dto.LoginDto;
import org.example.project_12.dto.RegisterDto;
import org.example.project_12.dto.UpdateUserDto;
import org.example.project_12.dto.UserDto;
import org.example.project_12.entity.Token;
import org.example.project_12.entity.User;
import org.example.project_12.mapper.TokenMapper;
import org.example.project_12.mapper.UserMapper;
import org.example.project_12.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenMapper tokenMapper;

    @Override
    @Transactional
    public User register(RegisterDto registerDto) {
        // 验证输入
        if (registerDto.getUsername() == null || registerDto.getUsername().trim().isEmpty()) {
            throw new RuntimeException("用户名不能为空");
        }
        if (registerDto.getPassword() == null || registerDto.getPassword().trim().isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }
        if (registerDto.getEmail() == null || registerDto.getEmail().trim().isEmpty()) {
            throw new RuntimeException("邮箱不能为空");
        }

        // 检查用户名是否已存在
        if (isUsernameExists(registerDto.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (isEmailExists(registerDto.getEmail())) {
            throw new RuntimeException("邮箱已存在");
        }

        // 创建用户
        User user = User.builder()
                .username(registerDto.getUsername().trim())
                .password(encryptPassword(registerDto.getPassword()))
                .email(registerDto.getEmail().trim())
                .role("USER") // 默认为普通用户
                .status("ACTIVE") // 注册即激活
                .build();
        
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(user.getCreatedAt());
        userMapper.insert(user);

        return user;
    }

    @Override
    @Transactional
    public String login(LoginDto loginDto) {
        // 验证输入
        if (loginDto.getUsername() == null || loginDto.getUsername().trim().isEmpty()) {
            throw new RuntimeException("用户名不能为空");
        }
        if (loginDto.getPassword() == null || loginDto.getPassword().trim().isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }

        // 查询用户
        User user = userMapper.selectByUsername(loginDto.getUsername().trim());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码
        if (!user.getPassword().equals(encryptPassword(loginDto.getPassword()))) {
            throw new RuntimeException("密码错误");
        }

        // 检查用户状态
        if (!"ACTIVE".equals(user.getStatus())) {
            throw new RuntimeException("账户未激活或已被禁用");
        }

        // 生成令牌
        String tokenString = generateToken();
        LocalDateTime expireTime = LocalDateTime.now().plusHours(24); // 24小时过期

        // 删除旧令牌
        tokenMapper.deleteByUserId(user.getId());

        // 保存新令牌
        Token token = Token.builder()
                .userId(user.getId())
                .tokenString(tokenString)
                .expireTime(expireTime)
                .build();
        token.setCreatedAt(LocalDateTime.now());
        tokenMapper.insert(token);

        return tokenString;
    }

    @Override
    @Transactional
    public boolean logout(String token) {
        if (token == null || token.trim().isEmpty()) {
            return false;
        }
        return tokenMapper.deleteByTokenString(token.trim()) > 0;
    }

    @Override
    public UserDto getUserInfo(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        return UserDto.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .role(user.getRole())
                .status(user.getStatus())
                .createdAt(user.getCreatedAt())
                .updatedAt(user.getUpdatedAt())
                .build();
    }

    @Override
    @Transactional
    public boolean updateUserInfo(Long userId, UpdateUserDto updateUserDto) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查用户名是否重复（排除当前用户）
        if (updateUserDto.getUsername() != null && !updateUserDto.getUsername().equals(user.getUsername())) {
            if (isUsernameExists(updateUserDto.getUsername())) {
                throw new RuntimeException("用户名已存在");
            }
            user.setUsername(updateUserDto.getUsername());
        }

        // 检查邮箱是否重复（排除当前用户）
        if (updateUserDto.getEmail() != null && !updateUserDto.getEmail().equals(user.getEmail())) {
            if (isEmailExists(updateUserDto.getEmail())) {
                throw new RuntimeException("邮箱已存在");
            }
            user.setEmail(updateUserDto.getEmail());
        }

        // 更新密码（如果提供）
        if (updateUserDto.getPassword() != null && !updateUserDto.getPassword().trim().isEmpty()) {
            user.setPassword(encryptPassword(updateUserDto.getPassword()));
        }

        user.setUpdatedAt(LocalDateTime.now());
        return userMapper.update(user) > 0;
    }

    @Override
    @Transactional
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证旧密码
        if (!user.getPassword().equals(encryptPassword(oldPassword))) {
            throw new RuntimeException("原密码错误");
        }

        // 更新密码
        user.setPassword(encryptPassword(newPassword));
        user.setUpdatedAt(LocalDateTime.now());
        return userMapper.update(user) > 0;
    }

    @Override
    public List<UserDto> getUserList(String status, String role) {
        User queryUser = new User();
        if (status != null && !status.trim().isEmpty()) {
            queryUser.setStatus(status);
        }
        if (role != null && !role.trim().isEmpty()) {
            queryUser.setRole(role);
        }

        List<User> users = userMapper.selectList(queryUser);
        List<UserDto> userDtos = new ArrayList<>();

        for (User user : users) {
            userDtos.add(UserDto.builder()
                    .id(user.getId())
                    .username(user.getUsername())
                    .email(user.getEmail())
                    .role(user.getRole())
                    .status(user.getStatus())
                    .createdAt(user.getCreatedAt())
                    .updatedAt(user.getUpdatedAt())
                    .build());
        }

        return userDtos;
    }

    @Override
    @Transactional
    public boolean approveUser(Long userId, String status) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        if (!"ACTIVE".equals(status) && !"REJECTED".equals(status)) {
            throw new RuntimeException("无效的状态值");
        }

        user.setStatus(status);
        user.setUpdatedAt(LocalDateTime.now());
        return userMapper.update(user) > 0;
    }

    @Override
    @Transactional
    public boolean toggleUserStatus(Long userId, String status) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        if (!"ACTIVE".equals(status) && !"DISABLED".equals(status)) {
            throw new RuntimeException("无效的状态值");
        }

        user.setStatus(status);
        user.setUpdatedAt(LocalDateTime.now());
        
        // 如果禁用用户，删除其令牌
        if ("DISABLED".equals(status)) {
            tokenMapper.deleteByUserId(userId);
        }
        
        return userMapper.update(user) > 0;
    }

    @Override
    public User validateToken(String token) {
        if (token == null || token.trim().isEmpty()) {
            return null;
        }

        Token tokenEntity = tokenMapper.selectByTokenString(token.trim());
        if (tokenEntity == null) {
            return null;
        }

        // 检查是否过期
        if (tokenEntity.getExpireTime().isBefore(LocalDateTime.now())) {
            tokenMapper.deleteByTokenString(token.trim());
            return null;
        }

        return userMapper.selectById(tokenEntity.getUserId());
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public User getUserById(Long userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public boolean isUsernameExists(String username) {
        User user = new User();
        user.setUsername(username);
        return userMapper.selectList(user).size() > 0;
    }

    @Override
    public boolean isEmailExists(String email) {
        User user = new User();
        user.setEmail(email);
        return userMapper.selectList(user).size() > 0;
    }

    /**
     * 加密密码
     */
    private String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    /**
     * 生成令牌
     */
    private String generateToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
